package com.ely.coupon.common.idempotent.interceptor;

import com.ely.coupon.common.idempotent.annotation.Idempotent;
import com.ely.coupon.common.idempotent.config.IdempotentProperties;
import com.ely.coupon.common.idempotent.service.TokenService;
import org.springframework.util.ObjectUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 *
 */
public class IdempotentTokenInterceptor implements HandlerInterceptor {
    @Resource
    private TokenService tokenService;

    /**
     * @param request  current HTTP request 请求对象
     * @param response current HTTP response  响应对象
     * @param handler  核心方法  Method 对象  Method
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Idempotent methodAnnotation = handlerMethod.getMethodAnnotation(Idempotent.class);
            if (!ObjectUtils.isEmpty(methodAnnotation)) {
                boolean b = tokenService.verifyToken(request);
                if (!b) {
                    response.getWriter().write("请勿重复提交");
                    return false;
                } else {
                    return true;
                }
            }
        }
        return true;
    }
}
